<?php

class ecRoute{
  
  public $isMatched = false;
  public $values;
  public $url;

  private $conditions;

  public function  __construct($url, $requestUri, $target, $conditions)
  {
    $this->url = $url;
    $this->values = array();
    $this->conditions = $conditions;

    $pNames = array();
    $pValues = array();

    preg_match_all('@:([\w]+)@', $url, $pNames, PREG_PATTERN_ORDER);

    $pNames = $pNames[0];

    $urlRegex = preg_replace_callback('@:[\w]+@', array($this, 'regexUrl'), $url);
    $urlRegex .= '/?';

    if (preg_match('@^' . $urlRegex . '$@', $requestUri, $pValues))
    {
      array_shift($pValues);

      foreach($pNames as $index => $value)
        $this->values[substr($value,1)] = $pValues[$index];

      foreach($target as $key => $value)
        $this->values[$key] = $value;

      $this->isMatched = true;
    }

    unset($pNames);
    unset($pValues);
  }

  public function regexUrl($matches)
  {
    $key = str_replace(':', '', $matches[0]);

    if (array_key_exists($key, $this->conditions))
    {
      return '('.$this->conditions[$key].')';
    }
    else
    {
      return '([a-zA-Z0-9_\+\-%]+)';
    }
  }
}